﻿using System;
using Nuwanda.Common;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Serialization;
using Nuwanda.TfsSpotlight.Shell.Services.Interfaces;
using StructureMap;

namespace Nuwanda.TfsSpotlight.Shell.Services
{
    [Author("Bartłomiej Legiędź")]
    [Pluggable("IsolatedStorageService")]
    public class IsolatedStorageService : IIsolatedStorageService
    {
        private readonly ILogger _logger;

        public IsolatedStorageService(ILogger logger)
        {
            this._logger = logger;
        }

        public void Save<T>(T entity, string fileName)
        {
            var storage = IsolatedStorageFile.GetUserStoreForAssembly();
            try
            {
                using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
                {
                    var xs = new XmlSerializer(typeof(T));
                    xs.Serialize(fs, entity);
                }
            }
            catch (Exception e)
            {
                this._logger.WriteException(e);
            }
            finally
            {
                storage.Close();
            }
        }

        public T Load<T>(string fileName)
        {
            var storage = IsolatedStorageFile.GetUserStoreForAssembly();
            try
            {
                using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
                {
                    var xs = new XmlSerializer(typeof(T));
                    return (T)xs.Deserialize(fs);
                }
            }
            catch (Exception e)
            {
                this._logger.WriteException(e);
            }
            finally
            {
                storage.Close();
            }

            return default(T);
        }
    }
}